//
//  SetPassWordViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/8/30.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "SetPassWordViewController.h"
#import "RentVieitor.h"


@interface SetPassWordViewController ()<UITextFieldDelegate>

@end

@implementation SetPassWordViewController {
    
    UITextField *passwordText;
    UITextField *passwordAgain;
    BOOL ischange;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    ischange = NO;
    self.title = @"设置密码";
    self.view.backgroundColor = BackgroundColor;
    [self creatLeftView];
    [self creatView];
    
}

- (void)creatLeftView {
    
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 80,15 );
    [leftBtn setImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
    [leftBtn setTitle:@"返回" forState:UIControlStateNormal];
    leftBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [leftBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [leftBtn setTitleColor:[Utils colorConvertFromString:@"#333333"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(0, 0, 50, 20);
    [rightBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor colorWithRed:225/255.0 green:141/255.0 blue:43/255.0 alpha:1] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
}

- (void)creatView {
    
    UIView *bdView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, KWidth, 50)];
    bdView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bdView];
    
    passwordText = [[UITextField alloc] initWithFrame:CGRectMake(20, 10, KWidth-30, 30)];
    passwordText.delegate = self;
    passwordText.textColor = [Utils colorConvertFromString:@"#333333"];
    passwordText.font = [UIFont systemFontOfSize:15];
    passwordText.secureTextEntry = YES;
    UIButton *canceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    canceBtn.frame = CGRectMake(0, 0, 17, 14);
    [canceBtn setBackgroundImage:[UIImage imageNamed:@"点击可见"] forState:UIControlStateNormal];
    [canceBtn setBackgroundImage:[UIImage imageNamed:@"点击可见"] forState:UIControlStateSelected];
    [canceBtn addTarget:self action:@selector(seeAction:) forControlEvents:UIControlEventTouchUpInside];
    passwordText.rightView = canceBtn;
    passwordText.rightViewMode = UITextFieldViewModeAlways;
    [bdView addSubview:passwordText];
    
    UILabel *proLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, KWidth, 15)];
    proLabel.text = @"请填写您的登录密码,由8-20位数字加字母构成";
    proLabel.textColor = [Utils colorConvertFromString:@"#666666"];
    proLabel.font = [UIFont systemFontOfSize:12];
    proLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:proLabel];
    
    UIView *bdView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 95, KWidth, 50)];
    bdView2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bdView2];
    passwordAgain = [[UITextField alloc] initWithFrame:CGRectMake(20, 10, KWidth-30, 30)];
    passwordAgain.delegate = self;
    passwordAgain.textColor = [Utils colorConvertFromString:@"#333333"];
    passwordAgain.font = [UIFont systemFontOfSize:15];
    passwordAgain.secureTextEntry = YES;
    [bdView2 addSubview:passwordAgain];
    
    UILabel *proLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 110, KWidth, 15)];
    proLabel2.text = @"请确认您的密码";
    proLabel2.textColor = [Utils colorConvertFromString:@"#666666"];
    proLabel2.font = [UIFont systemFontOfSize:12];
    proLabel2.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:proLabel2];
}

- (void)nextAction {
    
    if ([passwordText.text isEqualToString:passwordAgain.text] == NO) {
        
        [APPDELEGATE showPro:@"两次输入的密码不一致"];
    }
    
    if (passwordText.text.length < 8) {
        
        [APPDELEGATE showPro:@"密码长度必须8位或以上"];
        return;
    }
    
    //判断密码是否合格
    int judge = [self checkIsHaveNumAndLetter:passwordText.text];
    if (judge != 3) {
        
        [APPDELEGATE showPro:@"密码只能是字母+数字"];
        return;
    }
    
    NSDictionary *dataDic = User_listsValue;
    NSString *number = dataDic[@"number"];
    NSString *token = dataDic[@"token"];
    NSString *urlstr= [NSString stringWithFormat:@"%@member/safty/password",Main_Url];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@%@%@%@%@",self.auth,passwordText.text,passwordText.text,number,token,APPKEY_URL,urlstr];
    //32位小写
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    md5String = [md5String stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSDictionary *param = @{
                            @"number":number,
                            @"token":token,
                            @"auth":self.auth,
                            @"newpass":passwordText.text,
                            @"newpass2":passwordAgain.text,
                            @"sign":md5String
                            };
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    [manger POST:urlstr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSDictionary* jsonDic = [NSJSONSerialization
                                 JSONObjectWithData:responseObject
                                 options:kNilOptions
                                 error:nil];
        
        if ([jsonDic[@"code"] isEqualToString:@"10000"]) {
            
            [APPDELEGATE showEditSuccess:@"密码设置成功"];
            ischange = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"update" object:nil userInfo:nil];
            
            
        }else {
            
            [APPDELEGATE showPro:jsonDic[@"message"]];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [APPDELEGATE showPro:@"网络错误"];
    }];


}

- (void)seeAction:(UIButton *)button {
    
    button.selected = !button.selected;
    if (button.selected == YES) {
        passwordText.secureTextEntry = NO;
        passwordAgain.secureTextEntry = NO;
    }else {
        passwordText.secureTextEntry = YES;
        passwordAgain.secureTextEntry = YES;
    }
   
}

-(int)checkIsHaveNumAndLetter:(NSString*)password{
    //数字条件
    NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合数字条件的有几个字节
    NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:password
                                                                       options:NSMatchingReportProgress
                                                                         range:NSMakeRange(0, password.length)];
    
    //英文字条件
    NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合英文字条件的有几个字节
    NSUInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:password options:NSMatchingReportProgress range:NSMakeRange(0, password.length)];
    
    if (tNumMatchCount == password.length) {
        //全部符合数字，表示沒有英文
        return 1;
    } else if (tLetterMatchCount == password.length) {
        //全部符合英文，表示沒有数字
        return 2;
    } else if (tNumMatchCount + tLetterMatchCount == password.length) {
        //符合英文和符合数字条件的相加等于密码长度
        return 3;
    } else {
        return 4;
        //可能包含标点符号的情況，或是包含非英文的文字，这里再依照需求详细判断想呈现的错误
    }
    
}


- (void)backAction {
    
    if (ischange == YES) {
        
        
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

//结束编辑
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}
@end
